package com.ita.dao.impl;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ita.dao.BaseDao;


@SuppressWarnings("unchecked")
@Repository
public class BaseDaoImpl<T> implements BaseDao<T> {

	@PersistenceContext(name="unit")
	protected EntityManager em;

	@Override
	@Transactional
	public T add(T t) {
		em.persist(t);
		return t;
	}

	@Override
//	@Transactional
	public T delete(String id) {
		T tmp = (T) em.find(getClazz(), id);
		em.remove(tmp);
		return tmp;
	}

	@Override
//	@Transactional
	public T update(String id,T t) {
		T tmp = (T) em.find(getClazz(), id);
		em.remove(tmp);
		return add(t);
	}


	@Override
//	@Transactional
	public T select(String id) {
		return (T) em.find(getClazz(), id);
	}
	
	private Class<? super T> getClazz(){
		return (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];   
	}
	

}
